package com.example.trans.controller;

import com.example.trans.service.UserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/trans")
public class TransController {
    @Autowired
    private UserService userService;


    @Transactional
    @RequestMapping("/register")
    public Boolean register(String userName, String password) {

        Integer result = userService.register(userName,password);
        try {
            int a = 10 / 0;
        }catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }


    @Transactional
    @RequestMapping("/r2")
    public Boolean r2(String userName, String password) {

        Integer result = userService.register(userName,password);
        try {
            int a = 10 / 0;
        }catch (Exception e) {
            throw e;
        }

        return true;
    }


    @Transactional
    @RequestMapping("/r3")
    public Boolean r3(String userName, String password) {

        Integer result = userService.register(userName,password);
        try {
            int a = 10 / 0;
        }catch (Exception e) {
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return true;
    }


    @Transactional
    @RequestMapping("/r4")
    public Boolean r4(String userName, String password) throws IOException {

        Integer result = userService.register(userName,password);
        if (true) {
            throw new IOException();
        }

        return true;
    }

    @SneakyThrows
    @Transactional
    @RequestMapping("/r5")
    public Boolean r5(String userName, String password){

        Integer result = userService.register(userName,password);
        if (true) {
            throw new IOException();
        }

        return true;
    }



    @Transactional
    @RequestMapping("/r6")
    public Boolean r6(String userName, String password) throws IOException {

        Integer result = userService.register(userName,password);
        if (true) {
            throw new RuntimeException();
        }

        return true;
    }


    @Transactional(rollbackFor = Exception.class,isolation = Isolation.DEFAULT)
    @RequestMapping("/r7")
    public Boolean r7(String userName, String password) throws IOException {

        Integer result = userService.register(userName,password);
        if (true) {
            throw new IOException();
        }

        return true;
    }



}
